package com.spark.tags;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.spark.core.JacksonMapper;
import com.spark.core.SparkBuilder;
import com.spark.core.SparkContext;
import com.spark.core.XMap;

@SuppressWarnings("unchecked")
public class QueryForm extends ViewComponent {
	
	private static final String PROPERTITY_HEAD = "head";
	private static final String PROPERTITY_BODY = "body";
	private static final String BODY_CLASS = "s_qf_body";
	private static final String PROPERTITY_QUERY_BUTTON = "queryButton";
	
	protected int getDefaultWidth(){
		return 600;
	}
	
	public String execute(XMap view, SparkContext context) throws Exception{
		Integer width = (Integer)context.get(PROPERTITY_WIDTH);
		String id = (String)context.get(PROPERTITY_ID);
		StringBuilder sb = new StringBuilder();
		
		String style = (String)context.get(PROPERTITY_STYLE);
		sb.append("<div class=\"s_qf\" id=\""+id+"\" style=\""+style+";width:"+width+"px;\">");
        sb.append("<div class=\"s_qf_w\" style=\"width:"+width+"px;\">");
        
        context.openIdTrace();
        XMap head = view.getChild(PROPERTITY_HEAD);
        if(head != null){
			head.setName(HBox.TAG_NAME);
			head.putString(PROPERTITY_ID, id+"_head");
			sb.append(SparkBuilder.build(head, context));
        }
        XMap body = view.getChild(PROPERTITY_BODY);
        if(body!=null){
	        body.setName(Box.TAG_NAME);
	        String bstyle = body.getString(PROPERTITY_STYLE,"");
	        bstyle+=";display:none";
	        body.putString(PROPERTITY_STYLE,bstyle);
	        body.putString(PROPERTITY_CLASSNAME, BODY_CLASS);
	        body.putString(PROPERTITY_ID, id+"_body");
	        sb.append(SparkBuilder.build(body, context));
        }
        List idList = context.getIdList();
        context.closeIdTrace();
        
        sb.append("</div>");
        sb.append("<div class=\"s_shadow\" stype=\"shadow\"></div>");
        sb.append("</div>");
        String queryBtn = view.getString(PROPERTITY_QUERY_BUTTON,"");
        
        Map cfgMap = new HashMap();
        cfgMap.put("id", id);
        cfgMap.put("queryButton", queryBtn);
        cfgMap.put("child", idList);
        String config = JacksonMapper.getInstance().writeValueAsString(cfgMap);
        
        
        sb.append("<script>new Spark.QueryForm("+config+");</script>");
		return sb.toString();
	}
}
